<template>
	<!-- <view style="height:100vh;"> -->
	<!-- 网站类型 -->
	<view style="height:calc(100vh - 32px);">
		<u-toast ref="uToast"></u-toast>
		<!-- @scrolltoupper：上滑到顶部执行事件，此处用来加载历史消息 -->
		<!-- scroll-with-animation="true" 设置滚动条位置的时候使用动画过渡，让动作更加自然 -->
		<scroll-view :scroll-into-view="scrollToView" scroll-y="true" class="messageListScrollView"
			:style="{height:scrollViewHeight}" @scrolltoupper="getHistoryChat()"
			:scroll-with-animation="!isFirstListChat" ref="chatScrollView">
			<!-- 显示加载相关字样 -->
			<u-loadmore v-if="loadHistory==true" status="loading" />
			<view v-for="(message,index) in messageList" :key="message.id" :id="`message`+message.id"
				style="width: 750rpx;min-height: 60px;">
				<view style="height: 10px;"></view>
				<view v-if="message.type==0" class="messageItemLeft">
					<view style="width: 8px;"></view>
					<u--image :showLoading="true" :src="urlConstruct(you.avatar)" width="50px" height="50px"
						radius="3"></u--image>
					<view style="width: 7px;"></view>
					<view class="messageBubble">
						<bubble tailDirection="left" :text="message.content" backgroundColor="#ffffff" />
					</view>
				</view>
				<view v-if="message.type==1" class="messageItemRight">
					<view class="messageBubble">
						<bubble tailDirection="right" :text="message.content" backgroundColor="#95EC69" />
					</view>
					<view style="width: 7px;"></view>
					<u--image :showLoading="true" :src="urlConstruct(me.avatar)" width="50px" height="50px"
						radius="3"></u--image>
					<view style="width: 8px;"></view>
				</view>
			</view>
		</scroll-view>

		<view class="messageSend">
			<view class="messageInput">
				<u--textarea ref="textareaRef" v-model="messageInput" placeholder="请输入消息内容" autoHeight
					@focus="keyboardUp" @confirm="send()">
				</u--textarea>
			</view>
			<view style=" width:5px">
			</view>
			<view class="commmitButton" @click="send()">发 送</view>
		</view>
	</view>

</template>

<script>
	import {
		getUserProfileVo
	} from "@/api/user";
	import {
		listChat
	} from "@/api/market/chat.js";
	import Bubble from '@/components/bubble/bubble.vue';
	import {
		picUrlConstruct
	} from "@/utils/picUrlConstruct.js";

	let socket;
	import Vue from 'vue';
	export default {
		components: {
			Bubble
		},
		data() {
			return {
				webSocketUrl: "",
				socket: null,
				messageInput: '',
				// 我自己的信息
				me: {},
				// 对方信息
				you: {},

				scrollViewHeight: undefined,
				messageList: [],
				// 底部滑动到哪里
				scrollToView: '',
				page: {
					pageNum: 1,
					pageSize: 20
				},
				isFirstListChat: true,
				// 是否正在加载更多历史数据
				loadHistory: false,
				// 消息总条数
				total: 0,
				// 数据加载状态
				loadmoreStatus: "loadmore",
			}
		},
		created() {
			this.me = uni.getStorageSync("curUser");
		},
		beforeDestroy() {
			console.log("执行销毁方法");
			this.endChat();
		},
		onLoad(e) {
			this.checkSocket();
			// 设置初始高度
			if (this.Constant.softType == 0) {
				this.scrollViewHeight = `calc(100vh - 20px - 44px)`;
			} else if (this.Constant.softType == 1) {
				// 网站类型
				this.scrollViewHeight = `calc(100vh - 20px - 32px)`;
				// this.scrollViewHeight = `calc(100vh - 20px - 44px - 32px)`;
			}
			this.you = JSON.parse(decodeURIComponent(e.you));
			uni.setNavigationBarTitle({
				title: this.you.nickname,
			})
			this.startChat();
			this.listChat();
			this.receiveMessage();
		},

		onReady() {
			// 监听键盘高度变化，以便设置输入框的高度(适用于小程序，不适用于网站)
			uni.onKeyboardHeightChange(res => {
				if (this.Constant.softType == 0) {
					let keyBoardHeight = res.height;
					this.chatSuitable(keyBoardHeight);
				}
			})
		},

		methods: {
			urlConstruct(url) {
				return picUrlConstruct(url);
			},
			/**
			 * 键盘呼出（适用于网站）
			 */
			keyboardUp(value, height) {
				if (this.Constant.softType == 1) {
					this.chatSuitable(height);
				}
			},
			/**
			 * 键盘呼出时，聊天框自适应缩短
			 */
			chatSuitable(keyBoardHeight) {
				this.scrollViewHeight = `calc(100vh - 20px - 44px - ${keyBoardHeight}px)`;
				this.scrollToView = '';
				setTimeout(() => {
					this.scrollToView = 'message' + this.messageList[this
						.messageList.length - 1].id;
				}, 150)
			},
			/**
			 * 获取socket
			 */
			getSocket() {
				return this.Constant.softType === 0 ? this.$socket : this.$store.state.ws;
			},
			/**
			 * 检测socket是否正常
			 */
			checkSocket() {
				return new Promise((resolve, reject) => {
					let socket = this.getSocket();
					if (!socket) {
						// 连接已经断开，重新建立连接
						this.$webSocketService.initWebsocket(this.$store, this.Constant).then(() => {
							resolve();
						})
					} else {
						resolve();
					}
				})
			},
			/**
			 * 使用websocket发送消息
			 */
			sendByWebSocket(message) {
				this.checkSocket().then(() => {
					if (this.Constant.softType == 0) {
						this.$socket.send({
							data: JSON.stringify(message)
						});
					} else if (this.Constant.softType == 1) {
						// 网站类型
						this.$store.state.ws.send(JSON.stringify(message));
					}
				});
			},
			/**
			 * 发送消息
			 */
			send() {
				if (this.messageInput != '') {
					let message = {
						from: this.me.userName,
						to: this.you.username,
						text: this.messageInput
					}
					// console.log("this.socket.send:" + this.$socket)
					// 将组装好的json发送给服务端，由服务端进行转发
					this.sendByWebSocket(message);
					this.total++;
					let newMessage = {
						// code: this.messageList.length,
						type: 1,
						content: this.messageInput
					};
					this.messageList.push(newMessage);
					this.messageInput = '';
					this.toBottom();
				}
			},
			/**
			 * 开始聊天
			 */
			startChat() {
				let message = {
					from: this.me.userName,
					to: this.you.username,
					text: "",
					status: "start"
				}
				// 告诉服务端要开始聊天了
				this.sendByWebSocket(message);
			},
			/**
			 * 结束聊天
			 */
			endChat() {
				// 告诉服务端要结束聊天了
				let message = {
					from: this.me.userName,
					to: this.you.username,
					text: "",
					status: "end"
				}
				this.sendByWebSocket(message);
			},
			/**
			 * 接收消息
			 */
			receiveMessage() {
				this.checkSocket().then(() => {
					if (this.Constant.softType == 0) {
						this.$socket.onMessage((response) => {
							// console.log("接收消息：" + response.data);
							let message = JSON.parse(response.data);
							let newMessage = {
								// code: this.messageList.length,
								type: 0,
								content: message.text
							};
							this.messageList.push(newMessage);
							this.total++;
							// 让scroll-view自动滚动到最新的数据那里
							this.toBottom();
						})
					} else if (this.Constant.softType == 1) {
						// 网站类型
						let socket = this.$store.state.ws;
						let _that = this;
						socket.onmessage = function(response) {
							console.log("接收消息：" + response.data);
							let message = JSON.parse(response.data);
							let newMessage = {
								// code: this.messageList.length,
								type: 0,
								content: message.text
							};
							_that.messageList.push(newMessage);
							this.total++;
							// 让scroll-view自动滚动到最新的数据那里
							_that.toBottom();
						};
					}
				});

			},
			/**
			 * 查询对方和自己最近的聊天数据
			 */
			listChat() {
				return new Promise((resolve, reject) => {
					listChat(this.you.username, this.page).then(res => {
						for (var i = 0; i < res.rows.length; i++) {
							this.total = res.total;
							if (res.rows[i].fromWho == this.me.userName) {
								res.rows[i].type = 1;
							} else {
								res.rows[i].type = 0;
							}
							// 将消息放到数组的首位
							this.messageList.unshift(res.rows[i]);
						}

						if (this.isFirstListChat == true) {
							// this.$nextTick(function() {
							// 	// 滑动到聊天区域最底部
							// 	this.scrollToView = 'message' + this.messageList[this
							// 		.messageList.length - 1].id;
							// })
							this.isFirstListChat = false;
							this.toBottom();
						}
						resolve();
					})

				})

			},
			/**
			 * 滑到最顶端，分页加一，拉取更早的数据
			 */
			getHistoryChat() {
				// console.log("获取历史消息")
				if (this.messageList.length < this.total && this.loadHistory == false) {
					// 当目前的消息条数小于消息总量的时候，才去查历史消息
					this.page.pageNum++;
					this.loadHistory = true;
					this.scrollToView = '';
					this.listChat().then(() => {
						setTimeout(() => {
							this.loadHistory = false;
						}, 1000)
					})
				}
			},
			/**
			 * 滑动到聊天区域最底部
			 */
			toBottom() {
				// 让scroll-view自动滚动到最新的数据那里
				this.scrollToView = '';
				setTimeout(() => {
					// 滑动到聊天区域最底部
					this.scrollToView = 'message' + this.messageList[this
						.messageList.length - 1].id;
				}, 150)
			}
		}
	}
</script>

<style lang="scss">
	.messageListScrollView {
		background: #F5F5F5;
		// overflow: auto;

		.messageBubble {
			// max-width: calc(750rpx - 10px - 50px - 15px - 10px - 50px - 15px);
			// 网站类型
			max-width: calc(100% - 10px - 50px - 15px - 10px - 50px - 15px);
			padding: 0px 0px 10px 0px;
		}

		.messageItemLeft {
			display: flex;
			align-items: flex-start;
			justify-content: flex-start;
		}

		.messageItemRight {
			display: flex;
			align-items: flex-start;
			justify-content: flex-end;
		}
	}

	.messageSend {
		display: flex;

		background: #ffffff;
		padding-top: 5px;
		padding-bottom: 15px;

		.messageInput {
			border: 1px #EBEDF0 solid;
			border-radius: 5px;
			// width: calc(750rpx - 65px);
			// 网站类型
			width: calc(100% - 65px);
			margin-left: 5px;
		}

		.commmitButton {
			height: 38px;
			border-radius: 5px;
			width: 50px;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #ffffff;
			background: #3C9CFF;

		}
	}
</style>